<!--
  @Description:内容分页弹窗
  @Author: zqy
  @Date: 2020-07-21 14:15:12
  @Last Modified by:   zqy
  @Last Modified time: 2020-07-21 14:15:12
 -->
<template>
  <el-dialog
    ref="refDlg"
    :width="!single?'840px':'700px'"
    title="选择内容"
    :visible.sync="dialogShow"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    append-to-body
    @close="closeDialog"
  >
    <div class="table-main">
      <div class="table-left">
        <table-box
          ref="refTable"
          :table-config="tableConfig"
          :other-filters="otherFilters"
          :table-height="400"
          table-row-key="id"
          :table-sortable="false"
          :show-custom-combine="false"
          :show-custom-setting="false"
          :selected-arry.sync="tableSelected"
          :table-row-class-name="tableRowClassName"
          @selection-change="selectionChangeHandle"
          @data-change="tableDataChange"
          @row-dblclick="tableRowDblclick"
          @search-field-change="handleSearchFieldChange"
        >
          <el-table-column v-if="!single" slot="before" type="selection" reserve-selection width="40" />
        </table-box>
      </div>
      <div v-if="!single" class="table-right">
        <div class="qup-title-box"><span class="border" /><span>已选内容</span></div>
        <div class="table-list-box">
          <el-table
            style="width: 100%"
            :data="selectedRows"
            :height="400"
            header-row-class-name="table-list-header"
            highlight-current-row
            border
          >
            <el-table-column prop="name" label="名称" min-width="130" />
            <el-table-column prop="categoryName" label="所属类目" min-width="130" />
            <el-table-column label="操作" width="80" fixed="right">
              <template v-slot="{row}">
                <el-button class="my-button" type="text" size="mini" @click="delSelectedRow(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button size="mini" @click="closeDialog">取 消</el-button>
      <el-button type="primary" size="mini" @click="handleSure">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { parseTime } from '@/utils'
export default {
  name: 'ContentPageDlg',
  components: {},
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    // 是否单选（默认为单选）
    single: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      allTableData: [],
      otherFilters: [
        { id: 'state', property: 'state', operator: '=', value: 1 }
      ],
      searchField: '',
      tableConfig: {
        interfacePath: `${process.env.VUE_APP_BASE_API}/api/v1/helpCenterContent/pageContent`,
        onlySearchBar: true,
        tabIndex: 11,
        sort: 'lastUpdateTime',
        setting: [
          {
            prop: 'title',
            label: '名称',
            minWidth: 150
          },
          {
            prop: 'categoryName',
            label: '所属类目',
            minWidth: 120
          },
          {
            prop: 'lastUpdateBy',
            label: '修改人',
            type: 'hidden',
            minWidth: 120
          },
          {
            prop: 'lastUpdateTime',
            label: '修改时间',
            minWidth: 150,
            type: 'hidden',
            formatData: ({ lastUpdateTime }) => {
              return parseTime(lastUpdateTime)
            }
          }
        ]
      },
      selectedRows: [], // 多选行
      cancelSelectedRows: [], // 已取消选择的行
      tableSelected: [] // 单选行
    }
  },
  computed: {
    dialogShow: {
      get() {
        return this.visible
      },
      set(val) {
        this.$emit('update:visible', val)
      }
    }
  },
  watch: {
    dialogShow(val, oldVal) {
      if (!val) {
        this.tableSelected = []
        this.selectedRows = []
      }
    },
    allTableData: {
      handler(val, oldVal) {
        this.$nextTick(() => {
          this.reSetTableSelection()
        })
      },
      deep: true
    }
  },
  created() {
    /* this.otherFilters = [
      { id: '', property: '', value: '', operator: '=' }
    ] */
  },
  methods: {
    closeDialog() {
      this.selectedRows.forEach(row => {
        this.$refs.refTable.toggleRowSelection(row, false)
      })
      this.selectedRows = []
      this.tableSelected = []
      this.$emit('update:visible', false)
      this.$emit('close')
    },
    // 设置表格多选行高亮
    tableRowClassName({ row, rowIndex }) {
      const filterArr = this.selectedRows.filter(item => item.id === row.id)
      return filterArr.length > 0 ? 'selected-highlight' : ''
    },
    tableDataChange(data) {
      this.allTableData = (data && data.data && data.data.records) || []
    },
    // 重置当前页已选中数据的复选状态
    reSetTableSelection() {
      // 判断当前表数据中是存在已取消选中的数据，若存在，则取消表格数据的选中
      const delIds = []
      this.cancelSelectedRows.forEach(row => {
        const tmp = this.allTableData.filter(item => item.id === row.id)
        if (tmp.length > 0) { // 在当前页表格数据中则取消选中
          this.$refs.refTable.toggleRowSelection(tmp[0], false)
          delIds.push(row.id)
        }
      })
      delIds.forEach(id => {
        const index = this.cancelSelectedRows.findIndex(item => item.id === id)
        this.cancelSelectedRows.splice(index, 1)
      })
    },
    selectionChangeHandle(rows) {
      this.selectedRows = rows
    },
    // 移除已选择
    delSelectedRow(row) {
      const tmp = this.allTableData.filter(item => item.id === row.id)
      if (tmp.length > 0) { // 在当前页表格数据中则取消选中
        this.$refs.refTable.toggleRowSelection(tmp[0], false)
      } else { // 未在当前表格数据中，则加入到取消选中的数据集中，并从已选表中删除
        this.cancelSelectedRows.push(row)
        const index = this.selectedRows.indexOf(row)
        this.selectedRows.splice(index, 1)
      }
    },
    handleSure() {
      const selectTmp = this.single ? this.tableSelected : this.selectedRows
      if (selectTmp.length === 0) {
        this.$message.warning('请先选择关联内容')
        return
      }
      const rows = selectTmp.map(v => {
        return v
      })
      this.$emit('change', rows)
      this.closeDialog()
    },
    // 双击表格行
    tableRowDblclick(row, event) {
      if (!this.single) return
      this.selectedRows = [row]
      this.handleSure()
    },
    // 表格组件查询字段与查询值变更处理
    handleSearchFieldChange(params) {
      for (const key in params) {
        if (key !== this.searchField) {
          this.searchField = key
          if (params[key]) {
            this.$refs.refTable.$children[0].searchForm.searchVal = ''
          }
        }
      }
    }
  }
}
</script>

<style lang='scss' scoped>
  .table-main{
    width: 100%;
    display: flex;
    .table-left{
      width: 50%;
      box-sizing: border-box;
    }
    .table-right{
      width:350px;
    }
    .table-left{
      flex:1;
      padding-right: 10px;
    }
    .table-right{
      padding-left: 10px;
      .qup-title-box{
        line-height: 28px;
        height: 28px;
        margin-bottom: 10px;
      }
      // padding-top: 38px;
      .table-list-box{
        margin-top: 0;
      }
    }
  }

  /deep/ .pagination-info{
    display: none !important;
  }
</style>
